package com.tsj.spzx.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tsj.spzx.common.RedisStoredKey;
import com.tsj.spzx.exception.TsjException;
import com.tsj.spzx.mapper.SysRoleUserMapper;
import com.tsj.spzx.mapper.SysUserMapper;
import com.tsj.spzx.model.dto.system.AssginRoleDto;
import com.tsj.spzx.model.dto.system.LoginDto;
import com.tsj.spzx.model.dto.system.SysUserDto;
import com.tsj.spzx.model.entity.system.SysUser;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import com.tsj.spzx.model.vo.system.LoginVo;
import com.tsj.spzx.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Override
    public LoginVo login(LoginDto loginDto) {
        // 登录时，先判断验证码是否正确
        String codeValue = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();

        // 根据key获取redis中存储的验证码
        String storedCodeValue = redisTemplate.opsForValue().get(RedisStoredKey.VALIDATE_CODE_PREFIX + codeKey);
        if(StrUtil.isEmpty(storedCodeValue) || !StrUtil.equalsIgnoreCase(storedCodeValue,codeValue)){
            throw new TsjException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 都没有问题 删除redis中存储的验证码
        redisTemplate.delete(RedisStoredKey.VALIDATE_CODE_PREFIX + codeKey);

        // 获取用户名字
        String userName = loginDto.getUserName();
        // System.out.println(userName);
        // 根据名字去查询用户信息
        SysUser sysUser = sysUserMapper.findUserInfoByName(userName);

        if(sysUser == null){
            throw new TsjException(ResultCodeEnum.LOGIN_ERROR);
        }

        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());

        if(!input_password.equals(sysUser.getPassword())){
            throw new TsjException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        redisTemplate.opsForValue().set(
                RedisStoredKey.USER_LOGIN_TOKEN_PREFIX + token,
                JSON.toJSONString(sysUser),
                7,
                TimeUnit.DAYS
        );
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;

    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
//    @Override
//    public SysUser getUserInfoByToken(String token) {
//        String userJson = redisTemplate.opsForValue().get(RedisStoredKey.USER_LOGIN_TOKEN_PREFIX + token);
//        // 将json转成对象
//         return JSON.parseObject(userJson, SysUser.class);
//    }

    /**
     * 用户退出登录，根据token删除redis中存储的用户信息
     * @param token
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisStoredKey.USER_LOGIN_TOKEN_PREFIX + token);
    }

    /**
     * 用户信息条件分页查询
     * @param pageNum
     * @param pageSize
     * @param sysUserDto
     * @return
     */
    @Override
    public PageInfo<SysUser> finByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 添加用户
     * @param sysUser 封装前端传来的信息
     */
    @Override
    public void saveSysUser(SysUser sysUser) {
        //1 判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser dbSysUser = sysUserMapper.findUserInfoByName(userName);
        if(dbSysUser != null) {
            throw new TsjException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //2 输入密码进行加密
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);

        sysUserMapper.saveSysUser(sysUser);
    }

    /**
     * 修改用户信息
     * @param sysUser
     */
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    /**
     * 根据id删除用户
     * @param userId
     */
    @Override
    public void deleteSysUser(Integer userId) {
        sysUserMapper.deleteSysUser(userId);
    }

    /**
     * 为用户分配角色
     * 两个方法，添加事务注解
     * @param assginRoleDto 前端传来的数据 封装的是  用户userId和角色id列表roleIdList
     */
    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 1、先删除该用户原来分配的角色
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());
        // 2、重新分配角色
        sysRoleUserMapper.doAssign(assginRoleDto);
    }
}
